iT邦幫忙

2024 iThome 鐵人賽

DAY 15
0

在資料庫中,Commit 是一個命令,用來將一個交易(transaction)中所做的所有更改永久保存到資料庫中。當執行 commit 後,這些更改將不可逆,並且對其他資料庫用戶可見。

基本概念:

交易的開始:當你在資料庫中進行操作時(如 INSERT、UPDATE、DELETE),這些操作會被暫時保存,直到你決定是否要讓這些操作生效。

  • Commit:一旦確認所有操作都是正確的,執行 commit 後,這些更改會被永久寫入資料庫。
  • 在未執行 commit 前,其他資料庫用戶無法看到這些更改。
  • Rollback:如果操作有錯誤或你不想保存更改,執行 rollback 可以撤銷所有未提交的操作。

先前設定

在 JDBC 中,資料庫默認情況下是自動提交模式(auto-commit),如果我們想練習的話,要先關閉自動提交

connection.setAutoCommit(false);

在禁用自動提交之後,我們的程式如果沒有手動提交,那就不會寫東西進資料庫

public static void insertData(int number, String name, String gender, int age) {

        String insertSQL = "INSERT INTO student_information (number, name, gender, age) VALUES (?, ?, ?, ?)";

        try (Connection connection = DriverManager.getConnection(JDBC_url, JDBC_user, JDBC_password);
            PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) {

            connection.setAutoCommit(false);

            preparedStatement.setInt(1, number);
            preparedStatement.setString(2, name);
            preparedStatement.setString(3, gender );
            preparedStatement.setInt(4, age);

            int rowsAffected = preparedStatement.executeUpdate();
            
            connection.commit();
            
            if (rowsAffected > 0) {
                System.out.println("insert successful!" + rowsAffected + " row(s) affected.");
            }else {
                System.out.println("Insert failed");
            }

        } catch (SQLException e) {
            try {
                if (connection != null) {
                    connection.rollback();
                    System.out.println("Transaction rolled back.");
                }
            } catch (SQLException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                if (connection != null) {
                    connection.setAutoCommit(true);
                    connection.close();
                }
            } catch (SQLException closeEx) {
                closeEx.printStackTrace();
            }
        }
    }

我們的程式碼新增了

connection.commit();
和下面的try{}catch{}部分

這部分程式碼可以控制我們手動提交資料,下面是有提交成功的畫面
https://ithelp.ithome.com.tw/upload/images/20240929/20169406vMivJ1jUtI.png

如果把connetion.commit();去掉的話,雖然還是會顯示有資料進去,但是去資料庫查看並不會發現有新增東西,這個部份我還需要再學習一下...
https://ithelp.ithome.com.tw/upload/images/20240930/20169406FarOFZQdgD.png


上一篇
D14:SQL注入防範
下一篇
D16:學習Commit處理(下)
系列文
資料庫與Java開發工具連接26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言